<template>
  <div>
    <el-form ref="form" :model="spuInfo" label-width="80px">
      <el-form-item label="SPU名称">
        <el-input v-model="spuInfo.spuName"></el-input>
      </el-form-item>
      <el-form-item label="品牌">
        <el-select v-model="spuInfo.tmId">
          <el-option
            v-for="item in trademarkList"
            :key="item.id"
            :label="item.tmName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述">
        <el-input
          v-model="spuInfo.description"
          type="textarea"
          rows="4"
        ></el-input>
      </el-form-item>
      <el-form-item label="SPU图片">
        <el-upload
          action="/dev-api/admin/product/fileUpload"
          list-type="picture-card"
          :file-list="spuImageList"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-success="handleSuccess"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-select
          v-model="spuSaleAttrStr"
          :placeholder="`还有${
            unUseSaleAttrList && unUseSaleAttrList.length
          }个未选中`"
        >
          <el-option
            v-for="item in unUseSaleAttrList"
            :key="item.id"
            :label="item.name"
            :value="`${item.name}:${item.id}`"
          >
          </el-option>
        </el-select>
        <el-button
          type="primary"
          class="iconfont el-icon-plus"
          @click="addSaleAttr"
          :disabled="!spuSaleAttrStr"
          >添加销售属性</el-button
        >
        <el-table
          :data="spuInfo.spuSaleAttrList"
          style="width: 100%; margin: 20px 0"
          border
        >
          <el-table-column type="index" label="序号" width="80" align="center">
          </el-table-column>
          <el-table-column prop="saleAttrName" label="属性名" width="150">
          </el-table-column>
          <el-table-column label="属性值名称列表">
            <template slot-scope="{ row }">
              <el-tag
                :key="item.id"
                v-for="(item, index) in row.spuSaleAttrValueList"
                closable
                :disable-transitions="false"
                @close="handleClose(row.spuSaleAttrValueList, index)"
              >
                {{ item.saleAttrValueName }}
              </el-tag>
              <el-input
                class="input-new-tag"
                v-if="row.inputVisible"
                v-model="row.inputValue"
                ref="tagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm(row)"
                @blur="handleInputConfirm(row)"
              >
              </el-input>
              <el-button
                v-else
                class="button-new-tag"
                size="small"
                @click="showInput(row)"
                >+ 添加</el-button
              >
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template slot-scope="{ row }">
              <el-button
                type="danger"
                class="iconfont el-icon-delete"
                size="mini"
                @click="del(row)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" @click="save">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: "SpuForm",
  data() {
    return {
      // 照片墙数据
      dialogImageUrl: "",
      dialogVisible: false,

      // 标签数据
      // inputVisible: false,
      inputValue: "",

      // 图片列表
      spuImageList: [],
      // spu信息
      spuInfo: {
        spuImageList: [],
        spuSaleAttrList: [],
        category3Id: 0,
      },
      // 品牌信息
      trademarkList: [],
      // 销售属性
      baseSaleAttrList: [],
      // 销售属性值
      spuSaleAttrStr: "",
    };
  },
  props: ["category3Id"],
  methods: {
    // 照片墙功能
    // 删除照片触发
    handleRemove(file, fileList) {
      // 第一个参数是删除的图片信息，第二个参数是剩下数组的信息
      this.spuImageList = fileList;
    },
    // 点击查看大图会触发
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 上传图片成功会触发
    handleSuccess(response, file, fileList) {
      // console.log(response, file, fileList);
      let obj = {
        name: file.name,
        imgName: file.name,
        imgUrl: file.response.data,
        url: file.response.data,
      };
      this.spuImageList.push(obj);
    },
    // 如果是添加spu，就会进入这个函数获取数据
    initAddSpuInfo() {
      this.getTradeMarks();
      this.getBaseSaleAttrList();
    },
    // 如果是修改spu，就会调用这个函数获取数据
    initSpuInfo(row) {
      this.getSpuImageList(row.id);
      this.getSpuInfo(row.id);
      this.getTradeMarks();
      this.getBaseSaleAttrList();
    },
    // 获取spu的图片
    async getSpuImageList(id) {
      const { data } = await this.$API.sku.getSpuImageList(id);
      data.map((item) => {
        item.name = item.imgName;
        item.url = item.imgUrl;
      });
      this.spuImageList = data;
    },
    // 获取spu信息
    async getSpuInfo(id) {
      const { data } = await this.$API.spu.getSpuInfo(id);
      this.spuInfo = data;
    },
    // 获取品牌信息
    async getTradeMarks() {
      const { data } = await this.$API.trademark.getTradeMarks();
      this.trademarkList = data;
    },
    // 获取所有销售属性
    async getBaseSaleAttrList() {
      const { data } = await this.$API.spu.getBaseSaleAttrList();
      this.baseSaleAttrList = data;
    },
    // 添加销售属性
    addSaleAttr() {
      const { spuSaleAttrStr } = this;
      // 将它的值用：切割
      const [saleAttrName, baseSaleAttrId] = spuSaleAttrStr.split(":");
      const obj = {
        saleAttrName,
        baseSaleAttrId,
        spuSaleAttrValueList: [],
      };

      this.spuInfo.spuSaleAttrList.push(obj);
      this.spuSaleAttrStr = "";
    },

    // 删除tag标签
    handleClose(list, index) {
      list.splice(index, 1);
    },

    // 点击进入编辑模式
    showInput(row) {
      // this.inputVisible = true;

      // 因为是后续添加的属性，所以要让他变成响应式的
      this.$set(row, "inputVisible", true);

      // 因为渲染视图是异步的，所以需要调用nextTick
      this.$nextTick(() => {
        this.$refs.tagInput.focus();
      });
    },

    // 监视输入框失去焦点，自动进入展示模式
    handleInputConfirm(row) {
      let { inputValue } = row;

      // 如果属性值为空，就提示用户
      if (!inputValue.trim()) {
        this.$message.info("属性值不能为空");
        return;
      }

      // 如果属性值重复，也需要提示用户并且不能让用户继续输入下面的
      let repeat = row.spuSaleAttrValueList.some((item) => {
        return item.saleAttrValueName === inputValue;
      });
      if (repeat) {
        this.$message.info("属性值已存在，添加失败");
        return;
      }

      row.inputVisible = false;

      const obj = {
        baseSaleAttrId: row.baseSaleAttrId,
        saleAttrValueName: row.inputValue,
      };

      row.spuSaleAttrValueList.push(obj);

      row.inputValue = "";
    },
    // 删除销售属性
    del(row) {
      this.$confirm(`您确定要删除${row.saleAttrName}这个属性吗？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.spuInfo.spuSaleAttrList = this.spuInfo.spuSaleAttrList.filter(
            (item) => {
              return item.baseSaleAttrId !== row.baseSaleAttrId;
            }
          );
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 点击保存
    async save() {
      this.spuInfo.spuImageList = this.spuImageList;

      this.spuInfo.category3Id = this.category3Id;

      // 删除销售属性上添加的内容
      this.spuInfo.spuSaleAttrList.forEach((item) => {
        delete item.inputValue;
        delete item.inputVisible;
      });

      // 发送请求
      try {
        await this.$API.spu.addOrUpdate(this.spuInfo);
        this.$message.success("保存成功");
        // 重置当前组件状态
        this.resetData();
        // 隐藏spuForm页面
        this.$emit("update:visible", false);
        // 通知index重新请求页面
        this.$emit("success");
      } catch (error) {
        this.$message.info("保存失败");
      }
    },

    // 点击取消
    cancel() {
      this.$emit("update:visible", false);
      // 重置当前组件状态
      this.resetData();
      // 将flag改为false
      this.$emit("cancel");
    },
    // 重置当前组件状态
    resetData() {
      // Object.assign可以进行浅拷贝
      // this.$data可以获取当前data
      // this.$options.data()可以获取当前data中的数据
      Object.assign(this.$data, this.$options.data());
    },
  },
  computed: {
    unUseSaleAttrList() {
      const {
        baseSaleAttrList,
        spuInfo: { spuSaleAttrList },
      } = this;

      if (!baseSaleAttrList || !spuSaleAttrList) return;

      // 定义一个空对象
      let saleAttrObj = {};
      // 遍历较短的数组，将数组中有的id放入对象中,值为true
      spuSaleAttrList.forEach((item) => {
        saleAttrObj[item.baseSaleAttrId] = true;
      });
      // 在将长数组中的有id的过滤
      const unUseList = baseSaleAttrList.filter((item) => {
        return !saleAttrObj[item.id];
      });

      return unUseList;
    },
  },
};
</script>

<style>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
